package com.applink.sell_proof.database.table;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;

import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.database.EMarketingContentProvider;
import com.applink.sell_proof.model.Distributor;

public class DistributorDBHelper {
	public static final String TABLE_NAME = "distributor_table";
	public static final String DISTRIBUTOR_ID = "distributor_id";
	public static final String DISTRIBUTOR_NAME = "distributor_name";

	public static final String SQL_EXCUTE = "CREATE TABLE " + TABLE_NAME + "("
			+ DISTRIBUTOR_ID + " integer primary key ," + DISTRIBUTOR_NAME
			+ " text ," + TABLE_NAME + " text " + ");";

	public static void createDistributor(Distributor distributor) {
		ContentValues value = new ContentValues();
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();
		value.put(DISTRIBUTOR_ID, distributor.getId());
		value.put(DISTRIBUTOR_NAME, distributor.getName());

		resolver.insert(EMarketingContentProvider.DISTRIBUTOR_CONTENT_URI,
				value);
	}

	public static List<Distributor> getAllDistributor() {
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();
		Cursor cursor = resolver.query(
				EMarketingContentProvider.DISTRIBUTOR_CONTENT_URI, null, null,
				null, null);
		
		List<Distributor> distributors = new ArrayList<Distributor>();
		
		if (cursor != null) {
			
			while (cursor.moveToNext()) {
				Distributor distributor = new Distributor();
				distributor.setId(cursor.getLong(cursor
						.getColumnIndex(DISTRIBUTOR_ID)));
				distributor.setName(cursor.getString(cursor
						.getColumnIndex(DISTRIBUTOR_NAME)));
				distributors.add(distributor);
			}	
		}
		return distributors;
	}

	public static Distributor getDistributorById(long id) {
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		Cursor cursor = resolver
				.query(EMarketingContentProvider.DISTRIBUTOR_CONTENT_URI, null,
						DISTRIBUTOR_ID + "=?",
						new String[] { Long.toString(id) }, null);

		if (cursor != null && cursor.moveToFirst()) {
			Distributor distributor = new Distributor();
			distributor.setId(id);
			distributor.setName(cursor.getString(cursor
					.getColumnIndex(DISTRIBUTOR_NAME)));
			cursor.close();
			return distributor;
		}
		return null;
	}

}
